package com.jjty.dataGenerator.job;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jjty.dataGenerator.data.entity.vo.GeneratedData;
import com.jjty.dataGenerator.data.mapper.GeneratedDataMapper;
import com.jjty.dataGenerator.data.service.DataGeneratorService;
import com.jjty.dataGenerator.data.service.DataReportService;
import com.jjty.dataGenerator.data.service.OperationLogService;
import com.jjty.dataGenerator.jshjy.service.EduDataGenerateService;
import com.jjty.dataGenerator.sxhcampus.mapper.EsActiveDataMapper;
import com.jjty.dataGenerator.sxhcampus.service.SxHCampusService;
import com.jjty.dataGenerator.sxhcampus.vo.OAQueryOrderResult;
import com.jjty.dataGenerator.utils.TimeUtils;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

@Component
public class DataReportJob {

    @Autowired
    private DataReportService dataReportService;
    @Autowired
    SxHCampusService hCampusService;
    @Autowired
    private GeneratedDataMapper generatedDataMapper;
    @Autowired
    private DataGeneratorService dataGeneratorService;
    @Autowired
    private OperationLogService operationLogService;
    @Autowired
    private EsActiveDataMapper esActiveDataMapper;
    @Autowired
    private SxHCampusService sxHCampusService;
    @Autowired
    private EduDataGenerateService generateService;

    @XxlJob("dataReportJobHandler")
    public void dataReportJobHandler() throws Exception {
        String operationType = "数据自动上报任务";
        String operationIp = "localhost";
        String operationStatus;

        // 从 XXL-Job 参数中获取所需信息
        String param = XxlJobHelper.getJobParam();
        String[] params = param.split(",");
        //String schoolName = params[0];
        String dataType = params[0];
        String url = params[1];
        try {
            // 调用 reportData 方法
            dataReportService.reportData(dataType, url);
            operationStatus = "成功";
        }
        catch (Exception e) {
            operationStatus = "失败";
        }
        operationLogService.saveLog(operationType, operationIp, operationStatus,dataType);

        // 任务执行成功
        XxlJobHelper.handleSuccess();
    }


    @XxlJob("dataGenerateJobHandler")
    public ReturnT<String> dataGenerateJobHandler() throws Exception {
        String operationType = "数据自动生成任务";
        String operationIp = "localhost";
        String operationStatus;
        try {
            // 这里假设从XXL - Job参数中获取dataType和schoolNames
            // 格式为 "话机类,school1,school2" 类似这样
            String param = XxlJobHelper.getJobParam();
            if (param == null || param.isEmpty()) {
                XxlJobHelper.handleFail("任务参数为空");
                return ReturnT.FAIL;
            }
            String[] params = param.split(",");
            if (params.length < 2) {
                XxlJobHelper.handleFail("任务参数格式错误");
                return ReturnT.FAIL;
            }
            String dataType = params[0];
            String[] schoolNameArray = new String[params.length - 1];
            System.arraycopy(params, 1, schoolNameArray, 0, params.length - 1);
            operationStatus = "成功";
            operationLogService.saveLog(operationType, operationIp, operationStatus,dataType);
            dataGeneratorService.generateData(dataType, java.util.Arrays.asList(schoolNameArray));
            XxlJobHelper.handleSuccess();
            return ReturnT.SUCCESS;
        } catch (Exception e) {
            operationStatus = "失败";
            operationLogService.saveLog(operationType, operationIp, operationStatus,"1");
            XxlJobHelper.handleFail(e.getMessage());
            return ReturnT.FAIL;
        }
    }
    /**
     * 两部分：2023-08-01 到 2024-06-30
     * 2024-07-01 到 today
     */

    @XxlJob(value = "pushSxActiveDataAll", init = "init", destroy = "destroy")
    public void pushSxActiveDataAll() {
        esActiveDataMapper.delete(null);
        System.out.println("pushSxActiveDataAll");

        // 获取前一天的日期
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        Date yesterday = calendar.getTime();
        String yesterdayStr = TimeUtils.getFormat("yyyyMMdd", yesterday);

        // 前一天的开始时间和结束时间相同
        String startTime = yesterdayStr;
        String endTime = yesterdayStr;

        // provinceId=610000 查询陕西市
        // 获取前一天的数据
        try {
            HttpResponse<String> httpResponse = Unirest.get("https://oa.jiajiasports.com/openapi/order/listWithDate?startTime=" + startTime + "&endTime=" + endTime + "&provinceId=610000")
                    .asString();
            String body = httpResponse.getBody();
            OAQueryOrderResult result = JSONObject.parseObject(body, OAQueryOrderResult.class);
            int dataCount = result.getData().size();
            System.out.println("获取到陕西前一天的数据：" + dataCount + " 条");

            hCampusService.importActiveDataAll(result, startTime, endTime, "All" + yesterdayStr);
            System.out.println(startTime + " -> " + endTime + " :" + dataCount + " 条");
        } catch (Exception e) {
            System.out.println("获取数据或导入数据时出现异常:" + e);
        }
        hCampusService.transformAndSaveAllData();
        System.out.println("数据转换完成");
        hCampusService.sendAllActiveData();
        System.out.println("数据推送完成");


        System.out.println("执行完成");
    }
    // 实现 init 方法
    public void init() {
        // 初始化操作，可留空
        System.out.println("准备执行推送陕西活跃数据......");
    }

    // 实现 destroy 方法
    public void destroy() {
        // 销毁操作，可留空
        System.out.println("推送陕西活跃数据结束......");
    }

    @XxlJob("wechatNotificationJobHandler")
    public ReturnT<String> wechatNotificationJobHandler(String param) throws Exception {
        // 获取统计数据
        Map<String, Object> statisticsData = sxHCampusService.getStatisticsData();
        if (statisticsData != null) {
            int totalSuccess = (int) statisticsData.get("totalSuccess");
            int totalFailure = (int) statisticsData.get("totalFailure");
            Map<String, SxHCampusService.AgentResult> agentResultMap = (Map<String, SxHCampusService.AgentResult>) statisticsData.get("agentResultMap");

            // 发送企业微信通知
            sxHCampusService.sendWechatNotification(totalSuccess, totalFailure, agentResultMap);

            // 清空统计数据
            sxHCampusService.clearStatisticsData();
        }
        return ReturnT.SUCCESS;
    }

    @XxlJob(value = "cleanGeneratedDataJob")
    public void cleanGeneratedDataJob(HttpServletRequest request) throws Exception {
        String operationType = "数据自动清除任务";
        String operationIp = "localhost";
        String operationStatus;
        try {
            // 清空 generated_data 表的数据
            LambdaQueryWrapper<GeneratedData> queryWrapper = new LambdaQueryWrapper<>();
            generatedDataMapper.delete(queryWrapper);
            System.out.println("成功清空 generated_data 表的数据");
            operationStatus = "成功";
            operationLogService.saveLog(operationType, operationIp, operationStatus,"清除数据");
            // 任务执行成功
            XxlJobHelper.handleSuccess();
        } catch (Exception e) {
            System.err.println("清空 generated_data 表的数据时出错: " + e.getMessage());
            // 任务执行失败
            XxlJobHelper.handleFail("清空 generated_data 表的数据时出错: " + e.getMessage());
        }
    }
    /**
     * 定时生成心跳数据
     */
    @XxlJob("generateHeartbeatJob")
    public void generateHeartbeatJob() throws Exception {
        int count = 1;
        try {
            generateService.generateHeartbeatData(count);
            XxlJobHelper.handleSuccess("心跳数据生成成功，数量：" + count);
        } catch (Exception e) {
            XxlJobHelper.handleFail("心跳数据生成失败：" + e.getMessage());
        }
    }

    /**
     * 定时生成定位数据
     */
    @XxlJob("generateLocationJob")
    public void generateLocationJob() throws Exception {
        int count = 1;
        try {
            generateService.generateLocationData(count);
            XxlJobHelper.handleSuccess("定位数据生成成功，数量：" + count);
        } catch (Exception e) {
            XxlJobHelper.handleFail("定位数据生成失败：" + e.getMessage());
        }
    }

    /**
     * 定时生成通话数据
     */
    @XxlJob("generateCallJob")
    public void generateCallJob() throws Exception {
        int count = 1;
        try {
            generateService.generateCallData(count);
            XxlJobHelper.handleSuccess("通话数据生成成功，数量：" + count);
        } catch (Exception e) {
            XxlJobHelper.handleFail("通话数据生成失败：" + e.getMessage());
        }
    }

    /**
     * 定时生成考勤数据
     */
    @XxlJob("generateAttendanceJob")
    public void generateAttendanceJob() throws Exception {
        int count = 1;
        try {
            generateService.generateAttendanceData(count);
            XxlJobHelper.handleSuccess("考勤数据生成成功，数量：" + count);
        } catch (Exception e) {
            XxlJobHelper.handleFail("考勤数据生成失败：" + e.getMessage());
        }
    }
}